package com.sunny.netty.handler;

import com.sunny.netty.constants.EchoConstants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * 指定字符解析器服务端
 * @author sunny
 * @date 2018/12/6
 */
public class DelimiterFrameDecoderServerHandler extends ChannelInitializer {
    @Override
    protected void initChannel(Channel channel) throws Exception {
        ByteBuf delimiter = Unpooled.copiedBuffer(EchoConstants.SEPARATOR.getBytes());
        channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
        channel.pipeline().addLast(new StringDecoder());
        channel.pipeline().addLast(new DelimiterHandler());
    }

    private static class DelimiterHandler extends ChannelHandlerAdapter {

        private int counter;

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            String message = (String) msg;
            System.out.println("DelimiterHandler 接收到的消息：" + message + "; 当前统计：" + ++counter);
            message = message + EchoConstants.SEPARATOR;
            ByteBuf buf = Unpooled.copiedBuffer(message.getBytes());
            ctx.writeAndFlush(buf);
        }
    }

    public static void bind(int port) {
        //创建线程组
        NioEventLoopGroup masterGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            //创建NIO服务端启动辅助类
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(masterGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //服务端的连接数
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //服务端消息不延迟，立即推送
                    .option(ChannelOption.TCP_NODELAY, true)
                    //指定符号解码
                    .childHandler(new DelimiterFrameDecoderServerHandler());

            //绑定端口，同步等待成功
            System.out.println("绑定端口，同步等待成功。。。。");
            ChannelFuture future = bootstrap.bind(port).sync();

            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();
            System.out.println("等待服务端监听端口关闭。。。。");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //优雅退出释放线程池
            masterGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println("优雅退出释放线程池。。。。");
        }

    }

    public static void main(String[] args) {
        DelimiterFrameDecoderServerHandler.bind(4040);
    }
}
